package logic

import (
	"context"
	"errors"
	"video-joy/models/cache"
	"video-joy/models/mysql"
	"video-joy/pkg"

	"video-joy/userrpc/internal/svc"
	"video-joy/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePwdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePwdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePwdLogic {
	return &UpdatePwdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 密码重置
func (l *UpdatePwdLogic) UpdatePwd(in *userrpc.UpdatePwdRequest) (*userrpc.UpdatePwdResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.UserInfo

	if err := user.UserFindByPhone(mysql.DB, in.PhoneNum); err != nil {
		return nil, errors.New("该用户不存在")
	}

	if in.NewPwd != in.AckNewPwd {
		return nil, errors.New("两次密码不一致,请重新输入")
	}

	if pkg.Md5(in.NewPwd) == user.Pwd {
		return nil, errors.New("新密码和旧密码一致,请重新输入")
	}

	user.Pwd = pkg.Md5(in.NewPwd)

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.PhoneNum).Result()

	if result != in.SmsCode {
		return nil, errors.New("短信验证码错误,请重新输入")
	}

	if err := user.UpdatePwd(mysql.DB); err != nil {
		return nil, errors.New("修改失败")
	}

	return &userrpc.UpdatePwdResponse{
		UserId: int64(user.ID),
	}, nil
}
